import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/secure_vault/models/vault_item_model.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 添加私密信息对话框
class AddVaultItemDialog extends StatefulWidget {
  final String title;
  final String submitButtonText;
  final String? initialTitle;
  final VaultItemType? initialType;
  final String? initialUsername;
  final String? initialPassword;
  final String? initialUrl;
  final String? initialNotes;
  final Function(String title, VaultItemType type, String username,
      String password, String? url, String? notes) onSubmit;

  const AddVaultItemDialog({
    Key? key,
    this.title = '添加信息',
    this.submitButtonText = '添加',
    this.initialTitle,
    this.initialType,
    this.initialUsername,
    this.initialPassword,
    this.initialUrl,
    this.initialNotes,
    required this.onSubmit,
  }) : super(key: key);

  @override
  State<AddVaultItemDialog> createState() => _AddVaultItemDialogState();
}

class _AddVaultItemDialogState extends State<AddVaultItemDialog> {
  late TextEditingController _titleController;
  late TextEditingController _usernameController;
  late TextEditingController _passwordController;
  late TextEditingController _urlController;
  late TextEditingController _notesController;
  late VaultItemType _selectedType;
  bool _obscurePassword = true;
  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController(text: widget.initialTitle ?? '');
    _usernameController =
        TextEditingController(text: widget.initialUsername ?? '');
    _passwordController =
        TextEditingController(text: widget.initialPassword ?? '');
    _urlController = TextEditingController(text: widget.initialUrl ?? '');
    _notesController = TextEditingController(text: widget.initialNotes ?? '');
    _selectedType = widget.initialType ?? VaultItemType.website;
  }

  @override
  void dispose() {
    _titleController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _urlController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.r)),
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16.r),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // 标题
                Text(
                  widget.title,
                  style:
                      TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.center,
                ),
                SizedBox(height: 24.h),

                // 标题输入
                TextFormField(
                  controller: _titleController,
                  decoration: const InputDecoration(
                    labelText: '标题',
                    hintText: '网站或应用名称',
                    prefixIcon: Icon(Icons.title),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入标题';
                    }
                    return null;
                  },
                  autofocus: true,
                ),
                SizedBox(height: 16.h),

                // 类型选择
                DropdownButtonFormField<VaultItemType>(
                  value: _selectedType,
                  decoration: const InputDecoration(
                    labelText: '类型',
                    prefixIcon: Icon(Icons.category),
                  ),
                  items: VaultItemType.values.map((type) {
                    return DropdownMenuItem<VaultItemType>(
                      value: type,
                      child: Row(
                        children: [
                          Icon(type.icon,
                              size: 20.r, color: AppTheme.primaryColor),
                          SizedBox(width: 8.w),
                          Text(type.name),
                        ],
                      ),
                    );
                  }).toList(),
                  onChanged: (value) {
                    if (value != null) {
                      setState(() {
                        _selectedType = value;
                      });
                    }
                  },
                ),
                SizedBox(height: 16.h),

                // 用户名输入
                TextFormField(
                  controller: _usernameController,
                  decoration: const InputDecoration(
                    labelText: '用户名/账号',
                    hintText: '请输入用户名或账号',
                    prefixIcon: Icon(Icons.person),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入用户名或账号';
                    }
                    return null;
                  },
                ),
                SizedBox(height: 16.h),

                // 密码输入
                TextFormField(
                  controller: _passwordController,
                  obscureText: _obscurePassword,
                  decoration: InputDecoration(
                    labelText: '密码',
                    hintText: '请输入密码',
                    prefixIcon: const Icon(Icons.lock),
                    suffixIcon: IconButton(
                      icon: Icon(_obscurePassword
                          ? Icons.visibility
                          : Icons.visibility_off),
                      onPressed: () {
                        setState(() {
                          _obscurePassword = !_obscurePassword;
                        });
                      },
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '请输入密码';
                    }
                    return null;
                  },
                ),
                SizedBox(height: 16.h),

                // URL输入（可选）
                if (_selectedType == VaultItemType.website)
                  TextFormField(
                    controller: _urlController,
                    decoration: const InputDecoration(
                      labelText: '网址（可选）',
                      hintText: '请输入网站地址',
                      prefixIcon: Icon(Icons.link),
                    ),
                    keyboardType: TextInputType.url,
                  ),
                if (_selectedType == VaultItemType.website)
                  SizedBox(height: 16.h),

                // 备注输入（可选）
                TextFormField(
                  controller: _notesController,
                  decoration: const InputDecoration(
                    labelText: '备注（可选）',
                    hintText: '请输入备注信息',
                    prefixIcon: Icon(Icons.note),
                  ),
                  maxLines: 3,
                ),
                SizedBox(height: 24.h),

                // 按钮组
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(),
                      child: const Text('取消'),
                    ),
                    SizedBox(width: 16.w),
                    ElevatedButton(
                      onPressed: _submitForm,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppTheme.primaryColor,
                        foregroundColor: Colors.white,
                      ),
                      child: Text(widget.submitButtonText),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 提交表单
  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      final title = _titleController.text.trim();
      final username = _usernameController.text.trim();
      final password = _passwordController.text.trim();
      final url = _urlController.text.trim();
      final notes = _notesController.text.trim();

      widget.onSubmit(
        title,
        _selectedType,
        username,
        password,
        url.isNotEmpty ? url : null,
        notes.isNotEmpty ? notes : null,
      );
    }
  }
}
